package com.mlxg.master.service.impl;/**
 * @author zcy
 * @date 2025/6/9 14:07
 */

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlxg.master.domain.HzExhibitsReceive;
import com.mlxg.master.domain.HzInformation;
import com.mlxg.master.mapper.HzInformationSourceMapper;
import com.mlxg.master.service.HzInformationSourceService;
import com.mlxg.selver.domain.ExUserInformation;
import com.mlxg.selver.domain.ExhibitClassificationNode;
import com.mlxg.selver.domain.HzExhibitsSlave;
import com.mlxg.selver.domain.HzProductServicesIdMapping;
import com.mlxg.selver.domain.IdMapping;
import com.mlxg.selver.domain.base.BaseEntity;
import com.mlxg.selver.service.IExUserInformationService;
import com.mlxg.selver.service.IIdMappingService;
import com.mlxg.untils.oss.GeneralOSSUpLoadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zcy
 * @date 2025/6/9 14:07
 * @description: 老展商资料Service
 */
@Slf4j
@Service
@DS("master")
public class HzInformationSourceServiceImpl extends ServiceImpl<HzInformationSourceMapper, HzInformation> implements HzInformationSourceService {

    /**
     * old展商资料mapper
     */
    @Autowired
    private HzInformationSourceMapper hzInformationSourceMapper;

    /**
     * 通用文件上传
     */
    @Autowired
    private GeneralOSSUpLoadUtils generalOSSUpLoadUtils;

    @Autowired
    private ModelMapper modelMapper;

    /**
     * new 展商资料service
     */
    @Autowired
    private IExUserInformationService exUserInformationService;

    /**
     * 展商id映射
     */
    @Autowired
    private IIdMappingService iIdMappingService;

    /**
     * 展商资料迁移
     */
    @Override
    public void transferInformation() {

        int pageSize = 1000;
        int pageNum = 1;
        int totalProcessed = 0;
        int totalSuccess = 0;
        int totalFailed = 0;
        int totalPageFailed = 0;
        int noFindMapping = 0;
        log.info("开始展商资料数据迁移，每页处理 {} 条记录", pageSize);

        // 展商ID映射
        Map<String, IdMapping> exhibitorIdMappingConcurrentHashMap = new ConcurrentHashMap<>();


        QueryWrapper<HzInformation> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id", "exhibitor_id", "information_name", "sort", "audit_flag"
                , "del_flag", "remarks", "language", "url", "size");
        queryWrapper.in("del_flag", "0", "2");
        queryWrapper.in("audit_flag", "0", "2");
        queryWrapper.isNotNull("exhibitor_id");

        List<HzInformation> hzInformationList = null;
        do {
            try {
                // 分页查询
                Page<HzInformation> page = new Page<>(pageNum, pageSize);
                hzInformationList = hzInformationSourceMapper.selectPage(page, queryWrapper).getRecords();

                if (CollectionUtil.isEmpty(hzInformationList)) {
                    log.info("分页查询完成，没有更多数据，共处理 {} 页", pageNum - 1);
                    break;
                }

                // 记录总处理条数
                totalProcessed += hzInformationList.size();
                log.info("开始处理第 {} 页数据，当前页记录数: {}", pageNum, hzInformationList.size());

                int pageSuccess = 0;
                int pageFailed = 0;

                // 处理当前页的所有记录
                for (HzInformation oldHzInformation : hzInformationList) {
                    try {
                        log.debug("开始处理展商资料记录 - ID: {}", oldHzInformation.getId());

                        ExUserInformation newExUserInformation = modelMapper.map(oldHzInformation, ExUserInformation.class);

                        // 设置展商ID
                        String exhibitorId = oldHzInformation.getExhibitorId();
                        if (StringUtils.isEmpty(exhibitorId)) {
                            throw new RuntimeException("此展商资料没有绑定展商,数据ID: " + oldHzInformation.getId());
                        }

                        IdMapping idMapping = exhibitorIdMappingConcurrentHashMap.computeIfAbsent(exhibitorId,
                                key -> iIdMappingService.getById(key));

                        if (idMapping == null) {

                            noFindMapping++;
                            throw new RuntimeException("未找到展商ID映射关系，exhibitorId: " + exhibitorId);
                        }

                        // 设置展商ID
                        newExUserInformation.setUserId(idMapping.getUserId());


                        // 处理资料图片
                        newExUserInformation.setUrl(
                                processUrlField(oldHzInformation.getUrl(), "information"));
                        newExUserInformation.setAuditFlag(BaseEntity.AUDIT_FLAG_AUDITS);
                        newExUserInformation.setDelFlag(BaseEntity.DEL_FLAG_NORMALS);
                        if ("zh_CN".equals(oldHzInformation.getLanguage())){
                            newExUserInformation.setLanguage("zh-CN");
                        }else {
                            newExUserInformation.setLanguage("en-US");
                        }
                        // 保存新记录
                        exUserInformationService.save(newExUserInformation);
                        pageSuccess++;
                        totalSuccess++;
                        log.debug("展商资料记录处理成功 - ID: {}", oldHzInformation.getId());

                    } catch (Exception e) {
                        pageFailed++;
                        totalFailed++;
                        log.error("处理单条记录失败 - 数据ID: {}, 错误信息: {}",
                                oldHzInformation.getId(), e.getMessage(), e);
                    }
                }

                // 记录分页处理结果
                log.info("第 {} 页处理完成 - 成功: {}, 失败: {}", pageNum, pageSuccess, pageFailed);
                pageNum++;

            } catch (Exception e) {
                totalPageFailed++;
                log.error("处理第 {} 页数据失败，错误信息: {}", pageNum, e.getMessage(), e);
                pageNum++;
            }
        } while (hzInformationList != null && hzInformationList.size() == pageSize);

        log.info("数据迁移完成 - 总共处理页数: {}, 总记录数: {}, 成功: {}, 失败: {}, 分页处理失败: {},未找到展商id的映射关系一共={}",
                pageNum - 1, totalProcessed, totalSuccess, totalFailed, totalPageFailed, noFindMapping);

        // 记录迁移总结
        if (totalFailed > 0 || totalPageFailed > 0) {
            log.warn("数据迁移存在部分失败，请检查错误日志进行修复");
        } else {
            log.info("数据迁移全部成功完成");
        }
    }

    /**
     * 处理URL字段，将相对路径转换为OSS地址
     */
    /**
     * 处理URL字段，将相对路径转换为OSS地址
     */
    private String processUrlField(String fieldValue, String ossDir) {
        if (StringUtils.isBlank(fieldValue)) {
            return null;
        }
        if (fieldValue.startsWith("/")) {
            try {
                String url = generalOSSUpLoadUtils.uploadUrlToOss(fieldValue, ossDir);
                return url;
            } catch (IOException e) {
                return null;
            }
        } else if (fieldValue.startsWith("http://") || fieldValue.startsWith("https://")) {
            return fieldValue;
        }
        return null;
    }
}
